//
//  DSDialViewController.m
//  DS爱信
//
//  Created by 秦建英 on 14-5-27.
//  Copyright (c) 2014年 秦建英. All rights reserved.
//
#import "DSDialViewController.h"
#import "Header.h"
#import "AppDelegate.h"
#import "CallHisViewController.h"
#import "FMDBManager.h"
#import "DingSh.h"
#import "NetAccess.h"
#import "DSLgViewController.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "ViewController3.h"
@interface DSDialViewController ()<UIScrollViewDelegate,UIAlertViewDelegate,UITextFieldDelegate,NSURLConnectionDataDelegate>
@property (nonatomic,strong) UIPageControl *pageControl;
@end
#define CONFIGURE_BUTTON(BTN,X,Y,TITLE,TAG) {\
self.BTN = [UIButton buttonWithType:UIButtonTypeCustom];\
[self.BTN setFrame:CGRectMake(X, Y+10, widthOfButton, heightOfButton)];\
[self.BTN setTintColor:[UIColor whiteColor]];\
[self.BTN setBackgroundColor:[UIColor blackColor]];\
[self.BTN setTag:TAG];\
[self.BTN addTarget:self action:@selector(onKeyPressed:) \
forControlEvents:UIControlEventTouchUpInside];\
[_views addSubview:self.BTN];\
}
#define PULL_DOWN_OFFSET 5.0

#define TAG_KEY_DIAL     111

#define TAG_KEY_UNDO     444
@implementation DSDialViewController
{
    UITableView *_table;
    NSMutableArray *_images;
    UIScrollView *_scroll;
    NSMutableData *_data;
    NSMutableArray *_dataArraty;
   
    NSInteger count;
    NSUserDefaults *users;
    NSMutableArray *_call;
    NSMutableArray *_array;
    UIAlertView *_alertView;
    NSArray *_listItems;
    NSArray *_list;
    UIImageView *_imageView1;
    NSMutableArray *_df;
    NSString *_cs;
    NSArray *_plist;
    DSDialViewController *lg;
    NSMutableArray *_tellArray;
    AppDelegate *_app;
    NSString *_hj;
    UIButton *_btn;
    UIImageView * _imageg;
    NSTimer *_time;
    NSInteger select;
    UIView *contentView;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _dataArraty =[NSMutableArray array];
        users =[NSUserDefaults standardUserDefaults];
        _scroll =[[UIScrollView alloc]init];
        _array =[[NSMutableArray alloc]init];
        _views =[[UIView alloc]init];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    self.tabBarController.tabBar.hidden =NO;
    [_table reloadData];
    _views.hidden=NO;
    _btn.hidden =YES;
    _views.userInteractionEnabled =YES;
    [_table setHidden:NO];
    _scroll.hidden =NO;
    _pageControl.hidden = NO;
    _txtNumber.text =nil;
    self.navigationController.navigationBarHidden =YES;
    if(DeviceHeight==568)
    {
        _views.frame =CGRectMake(0, 195, DeviceWidth, DeviceHeight-195-49);
        _scroll.frame=CGRectMake(0, 0, DeviceWidth,DeviceHeight-_views.frame.size.height-49);
    }
    else
    {
        _views.frame =CGRectMake(0, 165, DeviceWidth, DeviceHeight-165-49);
        _scroll.frame=CGRectMake(0, 0, DeviceWidth,DeviceHeight-_views.frame.size.height-49);
    }
    [self.view addSubview:_views];
    [self inith];
    NSUserDefaults *us =[NSUserDefaults standardUserDefaults];
    _array =[us objectForKey:@"tellDemol"];
    _scroll.showsHorizontalScrollIndicator =NO;
    _scroll.showsVerticalScrollIndicator =NO;
    _scroll.bounces =NO;
    _scroll.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"2014.jpg"]];
    _scroll.delegate =self;
    _scroll.pagingEnabled =YES;
    _scroll.userInteractionEnabled =YES;
    [self.view addSubview:_scroll];
    // 小白点
    FMDBManager* manager = [FMDBManager sharedManager];
    _plist = [manager getAllUsers];
    [_table reloadData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hidden:) name:@"hidden" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chage:) name:@"textField" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ch:) name:@"tex" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hid:) name:@"hid" object:nil];
    
    _pageControl.numberOfPages = count;
    _pageControl.currentPage = select;
    _pageControl.userInteractionEnabled = NO;
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
   // [_pageControl bringSubviewToFront:_scroll];
    [self.view addSubview:_pageControl];

}
-(void)chage:(NSNotification *)notifition
{
    if (_txtNumber.text.length>0)
    {[self hideTabBar];
        _scroll.hidden =YES;
        _pageControl.hidden = YES;
        UIImageView *imafg =[[UIImageView alloc]init];
        imafg.backgroundColor =[UIColor blackColor];
        imafg.frame =CGRectMake(0, DeviceHeight-49, 320, 49);
        imafg.userInteractionEnabled =YES;
        _btn =[UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame =CGRectMake(20, 3, 280, 40);
        _btn.layer.cornerRadius =10;
        [_btn addTarget:self action:@selector(btck) forControlEvents:UIControlEventTouchUpInside];
        _btn.backgroundColor =[UIColor greenColor];
        UIImageView *image =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_end_call.png"]];
        image.frame =CGRectMake(120, 6, 35, 30);
        [_btn addSubview:image];
        [imafg addSubview:_btn];
        [self.view addSubview:imafg];
        self.view.frame=CGRectMake(0, 0, DeviceWidth, DeviceHeight);
        self.tabBarController.tabBar.hidden =YES;
    }
    NSString *tt=_txtNumber.text;
    
    _call =[[NSMutableArray alloc]init];
    
    for(int i=0;i<[_plist count];i++)
    {
        if([tt stringByAppendingString:tt])
        {
            NSString *sa=((DingSh *)[_plist objectAtIndex:i]).tel;
            NSString *ds =((DingSh *)[_plist objectAtIndex:i]).name;
            NSMutableArray *df =[[NSMutableArray alloc]initWithObjects:sa,ds, nil];
            NSString *gf =[df componentsJoinedByString:@","];
            NSRange range = [gf rangeOfString:tt];
            if(range.length > 0)
            {
                [_call addObject:gf];
            }
        }
    }
    [_table reloadData];
}
- (void)hideTabBar {
    
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
}
-(void)btck
{
    NSArray *array =[users objectForKey:@"users"];
    NSDictionary *dict =[array objectAtIndex:0];
    if([dict objectForKey:@"username"]==nil)
    {
        _alertView = [[UIAlertView alloc]initWithTitle:@"亲!还没绑定账号呢" message:nil delegate:self cancelButtonTitle:@"登录" otherButtonTitles:nil];
        _alertView.tag =2;
        [_alertView show];
        return;
    }
    else
    {
        [self dianji];
    }
}

-(void)loadImage
{
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://182.92.157.109/api/Advertisements?userid=2&tag=phone"]];
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
    NSURLConnection *connent =[[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connent start];
}
-(void)dianji
{
    if(_txtNumber.text.length)
    {
        _hj=@"未知联系人";
        NSMutableArray *sdk =[[NSMutableArray alloc]initWithObjects:_txtNumber.text,_hj,nil];
        NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
        if([myUserDefaults objectForKey:@"tellDemol"])
        {
            _tellArray = [[NSMutableArray alloc] initWithArray:[myUserDefaults objectForKey:@"tellDemol"]];
            NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
            if(_app.rarray.count>0)
            {
                [dict setObject:_txtNumber.text forKey:@"Demol"];
                [dict setObject:[_app.rarray objectAtIndex:0] forKey:@"Demolname"];
            }else
            {
                [dict setObject:_txtNumber.text forKey:@"Demol"];
                [dict setObject:_hj forKey:@"Demolname"];
            }
            [_tellArray addObject:dict];
            [myUserDefaults setObject:_tellArray forKey:@"tellDemol"];
        }
        else
        {
            _tellArray= [[NSMutableArray alloc] initWithCapacity:60];
            if(_tellArray.count>=60)
            {
                [_tellArray removeObjectAtIndex:0];
            }
            NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
            ;
            if(_app.rarray.count>0)
            {
                [dict setObject:_txtNumber.text forKey:@"Demol"];
                [dict setObject:[_app.rarray objectAtIndex:0] forKey:@"Demolname"];
            }else
            {
                [dict setObject:_txtNumber.text forKey:@"Demol"];
                [dict setObject:_hj forKey:@"Demolname"];
            }
            [_tellArray addObject:dict];
            [myUserDefaults setObject:_tellArray forKey:@"tellDemol"];
        }
        [myUserDefaults synchronize];
        [_table reloadData];
        CallHisViewController *cael =[[CallHisViewController alloc]init];
        cael.tellName=sdk;
        [self presentViewController:cael animated:YES completion:^{
            
        }];
    }
}
-(void)ch:(NSNotification *)notr
{self.tabBarController.tabBar.hidden =NO;
    _scroll.hidden =NO;
    _pageControl.hidden = NO;
    _btn.hidden =YES;
}
-(void)hidden:(NSNotification *)noti
{_scroll.hidden =YES;
    _pageControl.hidden = YES;
    [_call removeAllObjects];
    self.views.hidden =YES;
    [_table reloadData];
}
-(void)hid:(NSNotification *)noty
{
    _txtNumber.text =nil;
    self.views.hidden =NO;
    _scroll.hidden =NO;
    _pageControl.hidden = NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    count = 0;
    select = 0;
    self.view.backgroundColor =[UIColor whiteColor];
    NSUserDefaults *us =[NSUserDefaults standardUserDefaults];
    _array =[us objectForKey:@"tellDemol"];
    _table = [[ UITableView alloc ] initWithFrame : CGRectMake(0, 0, 320, DeviceHeight-49)];
    _table. delegate = self ;
    _table. dataSource = self ;
    [ self . view addSubview :_table];
    [self performSelectorInBackground:@selector(loadImage) withObject:self];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view removeFromSuperview];
    [_table setHidden:YES];
    [_alertView removeFromSuperview];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"hidden" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"textField" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tex" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"hid" object:nil];
}
- (NSInteger)numberOfSectionsInTableView:( UITableView *)tableView {
    return 1 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_call.count>0)
    {
        return [_call count];
    }
    else
    {
        return [_array count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"ContactCell" ;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleSubtitle reuseIdentifier :cellIdentifier];
        UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tab.png"]];
        imageView.frame =CGRectMake(0, 15, 30, 30);
        [cell addSubview:imageView];
        
        UIImageView *imag =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_calllog_call_normal.png"]];
        imag.frame =CGRectMake(285, 20, 23, 23);
        [cell addSubview:imag];
    }
    cell.textLabel.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:16];
    if(_call.count>0)
    {
        cell.textLabel.text=[NSString stringWithFormat:@"   %@",[_call objectAtIndex:indexPath.row]];
    }
    else if(_call.count<=0)
    {
        cell.textLabel.text=[NSString stringWithFormat:@"     %@       %@",[[_array objectAtIndex:indexPath.row] objectForKey:@"Demol"],[[_array objectAtIndex:indexPath.row] objectForKey:@"Demolname"]];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array =[users objectForKey:@"users"];
    NSDictionary *dict =[array objectAtIndex:0];
    if([dict objectForKey:@"username"]==nil)
    {
        _alertView = [[UIAlertView alloc]initWithTitle:@"亲!还没绑定账号呢" message:nil delegate:self cancelButtonTitle:@"登录" otherButtonTitles:nil];
        _alertView.tag =2;
        [_alertView show];
        return;
    }
    if(_call.count<=0)
    {_cs =[NSString stringWithFormat:@"%@,%@",[[_array objectAtIndex:indexPath.row] objectForKey:@"Demol"],[[_array objectAtIndex:indexPath.row] objectForKey:@"Demolname"]];
    }
    else
    {
        _cs =[NSString stringWithFormat:@"%@",[_call objectAtIndex:indexPath.row]];
    }
    _listItems = [_cs componentsSeparatedByString:@","];
    if(IOS5==YES)
    {
        [self compar];
    }
    else
    {
        _alertView = [[UIAlertView alloc]initWithTitle:@"亲！您是要拨号么" message:nil delegate:self cancelButtonTitle:@"呼叫" otherButtonTitles:@"取消",nil];
        _alertView.tag =1;
        [_alertView show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag ==1)
    {
        if(buttonIndex==0)
        {
            [self compar];
        }
        else
            NSLog(@"quxiao");
    }
    if(alertView.tag==2)
    {
        DSLgViewController *deng =[[DSLgViewController alloc]init];
        [self presentViewController:deng animated:YES completion:^{
            
        }];

    }
}
-(void)compar
{
    CallHisViewController *call =[[CallHisViewController alloc]init];
    AppDelegate *app =[UIApplication sharedApplication].delegate;
    [app.rarray removeAllObjects];
    if(_listItems.count<=1)
    {
        NSString *gh =@"未知联系人";
        [app.rarray addObject:gh];
    }
    else
    {
        [app.rarray addObject:[_listItems objectAtIndex:1]];
    }
    call.tellName =_listItems;
    [self presentViewController:call animated:YES completion:^{
        
    }];
}
-(void)inith
{
    _tellArray =[NSMutableArray array];
    _app =[UIApplication sharedApplication].delegate;
    CGRect frame = [[UIScreen mainScreen]applicationFrame];
    frame.size.height /= 1.1;
    if (self) {
        CGFloat heightOfTextField = 30.0;
        CGFloat widthOfButtonOnOff = 40.0;
        self.txtNumber = [[UITextField alloc]initWithFrame:CGRectMake(10,3,320-80,heightOfTextField+5)];
        [self.txtNumber setBorderStyle:UITextBorderStyleRoundedRect];
        [self.txtNumber setEnabled:NO];
        self.txtNumber.font=[UIFont fontWithName:@"Times New Roman" size:28];
        self.txtNumber.adjustsFontSizeToFitWidth=YES;
        [self.txtNumber setPlaceholder:@"号码:  固话前请加拨区号"];
        self.txtNumber.text =@"";
        self.txtNumber.backgroundColor =[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
        self.txtNumber.delegate = self;
        [_views addSubview:self.txtNumber];
        
        self.btnOffOn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.btnOffOn setFrame:CGRectMake(self.txtNumber.frame.size.width+8, -15, widthOfButtonOnOff+25, heightOfTextField+35)];
        [self.btnOffOn setBackgroundImage:[UIImage imageNamed:@"btn_imemoji_del_down.png"]
                                 forState:UIControlStateNormal];
        [self.btnOffOn addTarget:self
                          action:@selector(onButtonOnOffPressed:)
                forControlEvents:UIControlEventTouchUpInside];
        self.btnOffOn.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
        [_views addSubview:self.btnOffOn];
        
        CGFloat heightOfButton = frame.size.height / 5.0 - heightOfTextField;
        CGFloat widthOfButton = frame.size.width / 3.0;
        //configure the number key
        CONFIGURE_BUTTON(btn1, 0, heightOfTextField, @"1",1);
        [self.btn1 setBackgroundImage:[UIImage imageNamed:@"numpad_one.png"]
                             forState:UIControlStateNormal];
        self.btn1.selected =YES;
        CONFIGURE_BUTTON(btn2, widthOfButton , heightOfTextField, @"2",2);
        [self.btn2 setBackgroundImage:[UIImage imageNamed:@"numpad_two.png"]
                             forState:UIControlStateNormal];
        self.btn2.selected =YES;
        CONFIGURE_BUTTON(btn3, widthOfButton*2, heightOfTextField, @"3",3);
        [self.btn3 setBackgroundImage:[UIImage imageNamed:@"numpad_three.png"]
                             forState:UIControlStateNormal];
        self.btn3.selected =YES;
        CONFIGURE_BUTTON(btn4, 0, heightOfButton + heightOfTextField, @"4",4);
        [self.btn4 setBackgroundImage:[UIImage imageNamed:@"numpad_four.png"]
                             forState:UIControlStateNormal];
        self.btn4.selected =YES;
        CONFIGURE_BUTTON(btn5, widthOfButton, heightOfButton + heightOfTextField, @"5",5);
        [self.btn5 setBackgroundImage:[UIImage imageNamed:@"numpad_five.png"]
                             forState:UIControlStateNormal];
        self.btn5.selected =YES;
        CONFIGURE_BUTTON(btn6, widthOfButton*2, heightOfButton + heightOfTextField, @"6",6);
        [self.btn6 setBackgroundImage:[UIImage imageNamed:@"numpad_six.png"]
                             forState:UIControlStateNormal];
        self.btn6.selected =YES;
        CONFIGURE_BUTTON(btn7, 0, heightOfButton*2 + heightOfTextField, @"7",7);
        [self.btn7 setBackgroundImage:[UIImage imageNamed:@"numpad_seven.png"]
                             forState:UIControlStateNormal];
        self.btn7.selected =YES;
        CONFIGURE_BUTTON(btn8, widthOfButton, heightOfButton*2 + heightOfTextField, @"8",8);
        [self.btn8 setBackgroundImage:[UIImage imageNamed:@"numpad_eight.png"]
                             forState:UIControlStateNormal];
        self.btn8.selected =YES;
        CONFIGURE_BUTTON(btn9, widthOfButton*2, heightOfButton*2 + heightOfTextField, @"9",9);
        [self.btn9 setBackgroundImage:[UIImage imageNamed:@"numpad_nine.png"]
                             forState:UIControlStateNormal];
        self.btn9.selected =YES;
        CONFIGURE_BUTTON(btn0, widthOfButton, heightOfButton*3 + heightOfTextField, @"0",0);
        [self.btn0 setBackgroundImage:[UIImage imageNamed:@"numpad_zero.png"]
                             forState:UIControlStateNormal];
        self.btn0.selected =YES;
        CONFIGURE_BUTTON(btnDial,0,heightOfButton*3 + heightOfTextField, @"Dial",TAG_KEY_DIAL);
        [self.btnDial  setBackgroundImage:[UIImage imageNamed:@"numpad_star.png"]forState:UIControlStateNormal];
        self.btnDial.selected =YES;
        CONFIGURE_BUTTON(btnUndo, widthOfButton*2, heightOfButton*3 + heightOfTextField, @"Undo",TAG_KEY_UNDO);
        [self.btnUndo setBackgroundImage:[UIImage imageNamed:@"numpad_sharp.png"]
                                forState:UIControlStateNormal];
        self.btnUndo.selected =YES;
        mIsLayOn = NO;
        [self setLayOn:mIsLayOn];
        _views.backgroundColor = [UIColor blackColor];
    }
}
-(void)setLayOn:(BOOL)isLayOn
{
    CGFloat adjustOffset = (_views.frame.size.height )/8.0 + PULL_DOWN_OFFSET;
    if (isLayOn == YES) {
        adjustOffset *= 1;
    }
}
-(void)onKeyPressed:(id)sender
{
    NSInteger tag = [sender tag];
    NSString *text = self.txtNumber.text;
    switch (tag) {
        case TAG_KEY_DIAL:
            if (TAG_KEY_DIAL) {
//                {
                    self.txtNumber.text =[NSString stringWithFormat:@"%@",[text stringByAppendingString:@"*"]];
                //}
            }
            break;
        case TAG_KEY_UNDO:
            if (TAG_KEY_UNDO) {
                self.txtNumber.text =[NSString stringWithFormat:@"%@",[text stringByAppendingString:@"#"]];
            }
            break;
        default:
            self.txtNumber.text = [NSString stringWithFormat:@"%@%d",text,tag];
            if(self.txtNumber.text .length>0)
            {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"textField" object:self.txtNumber.text];
            }
            break;
    }
}
-(void)onButtonOnOffPressed:(id)sender
{NSString *text = self.txtNumber.text;
    if (text.length) {
        self.txtNumber.text = [text stringByReplacingCharactersInRange:NSMakeRange(text.length-1, 1)withString:@""];
        if(self.txtNumber.text.length==0)
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"tex" object:self.txtNumber.text];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark--网络代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   
 
    NSError* error;
    id jsonObect = [NSJSONSerialization JSONObjectWithData:_data
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    NSLog(@"%@",jsonObect);
    if ([jsonObect objectForKey:@"success"]  && error == nil)
    {
        
        NSNumber* ff =  [jsonObect objectForKey:@"total"];
        count = [ff intValue];
        _dataArraty = [jsonObect objectForKey:@"ads"];
        for (id item in _dataArraty)
        {
            NSLog(@"item = %@",item);
            
        }
        [self scrollViewImageInit];
    }
    else
    {
        NSLog(@"error = %@",error);
    }
    
}

-(void)scrollViewImageInit
{
    NSLog(@"inti");
    _scroll.pagingEnabled = YES;
    _scroll.delegate = self;
    _scroll.contentSize = CGSizeMake(DeviceWidth*count, _scroll.frame.size.height);
    _scroll.autoresizesSubviews = YES;
    for (int i=0; i<count; i++) {
        
        UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(i*_scroll.frame.size.width, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        //view.image = [UIImage imageNamed:@"base_detail_default_pic.png"];
        NSString* iamgePAth = [[_dataArraty objectAtIndex:i] objectForKey:@"PicPath"];
        NSLog(@"PATH = %@",iamgePAth);
        NSNumber* tagId = [[_dataArraty objectAtIndex:i] objectForKey:@"Id"];
        view.tag = i;
        [view setImageWithURL:[NSURL URLWithString:iamgePAth] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
      
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        tapGesture.numberOfTapsRequired = 1;
        [view addGestureRecognizer:tapGesture];
        view.userInteractionEnabled = YES;
        [_scroll addSubview:view];
        
    }
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(250, _scroll.frame.size.height-20, 60, 20)];
    _pageControl.numberOfPages = count;
    _pageControl.currentPage = select;
    _pageControl.userInteractionEnabled = NO;
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    // [_pageControl bringSubviewToFront:_scroll];
    [self.view addSubview:_pageControl];
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSString *message =@"亲！网络不给力啊，稍后再试吧..!";
    //_alertView.message = message;
    //[_alertView show];
    [self performSelector:@selector(loadImage) withObject:nil afterDelay:0.0];
    NSLog(@"数据下载失败");
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_scroll]) {
        
        NSInteger page = fabs(scrollView.contentOffset.x/scrollView.frame.size.width);
        _pageControl.currentPage = page;
        select = _pageControl.currentPage;
        
    }
}
- (void)tap:(id)sender
{
    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
    if(tap.numberOfTapsRequired == 1)
    {
        NSString *newId = [NSString stringWithFormat:@"%ld",(long)tap.view.tag];
        NSLog(@"id = %@",newId);
        ViewController3* viewConttoller = [[ViewController3 alloc] init];
        viewConttoller.dic = [_dataArraty objectAtIndex:select];
        UINavigationController* nav  =[[UINavigationController alloc] initWithRootViewController:viewConttoller];
        [self.navigationController presentModalViewController:nav  animated:YES];
        
        
    }
    
   
}


@end
